package cn.wolfcode.exception;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ControllerAdviceForException {
        @ExceptionHandler(RuntimeException.class)
        /**
         * 捕获运行过程中出现的运行时异常
         */
    public String handleException(Model model, RuntimeException ex,
                                  HandlerMethod handlerMethod, HttpServletResponse response) throws IOException {
            //把异常信息打印出来 方便我们开发的生活找bug
            ex.printStackTrace();
            //判断当前页面是否是ajax的方法贴了@ReqyuredPermission注解 如果贴了就要返回JsonResult 如果没贴就要返回错误视图
            //如果是,则返回jsonresult
            if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
                    JsonResult jsonResult = new JsonResult(false,"错误信息,请联系管理员");
                //使用response对象输出数据(json字符串)
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().print(JSON.toJSONString(jsonResult));
                return null;
            }
                //如果不是 就返回错误视图
            model.addAttribute("ex",ex);
                return "common/error";//返回的错误视图

        }
}
